package dev.tools.view.dialogs;

import dev.tools.design.patterns.command.Command;
import dev.tools.design.patterns.state.IStateHandler;
import dev.tools.design.patterns.state.StateChanged;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created with IntelliJ IDEA.
 * User: Nuno
 * Date: 01-10-2013
 * Time: 18:42
 */
public abstract class FormDialog<TCommand extends Command> extends GridBagDialog {
    protected final TCommand command;
    private int numberOfFields = 0;


    protected FormDialog(JFrame frame, final TCommand command) {
        super(frame);
        this.command = command;

        addButton("Submit").addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setEnabled(false);

                JProgressBar progressBar = new JProgressBar();
                progressBar.setIndeterminate(true);
                getButtonsPanel().removeAll();
                getButtonsPanel().add(progressBar, BorderLayout.SOUTH);

                pack();
                onExecuting();
                new Thread() {

                    @Override
                    public void run() {
                        command.addHandler(new IStateHandler<Command, Command.State>() {
                            @Override
                            public void update(Command context, StateChanged stateChanged) {
                                setVisible(false);
                            }
                        }, Command.FINISHED).execute();
                    }
                }.start();
            }
        });
    }

    protected void onExecuting() {
    }

    protected <T extends Component> T addField(String name, T field) {
        setComponent(0, numberOfFields, new JLabel(name));
        setComponent(1, numberOfFields++, field);

        return field;
    }

    public FormDialog onCommandFinished(IStateHandler<Command, Command.State> handler){
        command.addHandler(handler, Command.FINISHED);

        return this;
    }
}
